﻿using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using WebMonitor.Http;
using WebMonitor.Http.Impl;

namespace WebMonitor {
    public abstract class Controller : IHttpHandler, IController {
        public virtual string FillResponseTemplate(IDictionary<string, object> viewParams) {
            var engine = new VelocityEngine();
            var props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "assembly");
            props.AddProperty("assembly.resource.loader.class",
                              "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity");
            props.AddProperty("assembly.resource.loader.assembly", GetType().Assembly.FullName);
            engine.Init(props);
            var vcontext = new VelocityContext();
            foreach (var k in viewParams) {
                vcontext.Put(k.Key, k.Value);
            }
            using (var writer = new StringWriter()) {
                engine.GetTemplate(ViewName).Merge(vcontext, writer);
                return writer.GetStringBuilder().ToString();
            }
        }

        public void ProcessRequest(HttpContext context) {
            var viewParams = Execute(new HttpContextAdapter(context));
            context.Response.Write(FillResponseTemplate(viewParams));
        }

        public virtual string ControllerName {
            get { return Regex.Replace(GetType().Name, "Controller$", ""); }
        }

        public virtual string ViewName {
            get { return string.Format("{0}.Resources.{1}.html", GetType().Assembly.FullName.Split(',')[0], ControllerName); }
        }

        public bool IsReusable {
            get { return false; }
        }

        public abstract IDictionary<string, object> Execute(IHttpContext context);
    }
}